package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.PageInfo;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import com.itheima.vo.EmployeeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public EmployeeVo login(String username, String password) {
        Employee employee = employeeMapper.selectByUsernameAnePassword(username, password);

        //判断员工是否存在
        if (employee == null) {
            return null;
        }

        //旧的封装方法
//        EmployeeVo employeeVo = new EmployeeVo();
//        employeeVo.setUsername(employee.getUsername());


        //token   要求：唯一、安全
        String token = employee.getId() + System.currentTimeMillis() + employee.getId();

        //定义一个key
//        String key="123qweQWE!@#";
//        Map<String,Object> map= new HashMap<>();//map默认大小16
//        map.put("username",employee.getUsername());
//        String token = JWTUtil.createToken(map, key.getBytes());


        //存入redis数据库                                            //对象转换成json字符串         设置token过期时间，下面设置30分钟
        redisTemplate.opsForValue().set("employee_token:" + token, JSON.toJSONString(employee), 30, TimeUnit.MINUTES);


        //封装数据----新方法   bean工具类  BeanUtils.copyProperties将来源复制到目标
        EmployeeVo employeeVo = new EmployeeVo();
        BeanUtils.copyProperties(employee, employeeVo);
        employeeVo.setToken(token);

        return employeeVo;
    }

    //退出时清理token
    @Override
    public void clearToken(String token) {
        redisTemplate.delete("employee_token:" + token);
        //不需要判空，能执行到这步证明有内容，否则拦截器都无法通过
    }


    //根据Id查询用户
    @Override
    public EmployeeVo getById(String id) {
        Employee employee = employeeMapper.getById(id);
        EmployeeVo employeeVo = new EmployeeVo();
        //bean工具类  BeanUtils.copyProperties将来源(employee)复制到目标(employeeVo).填充相同字段
        BeanUtils.copyProperties(employee, employeeVo);
        return employeeVo;
    }


    @Override
    //分页    下面的<Employee>是因为PageInfo自定义了一个泛型<T>
    public PageInfo<Employee> page(String name, Integer page, Integer pageSize) {
        //创建一个容器
        PageInfo<Employee> pageInfo = new PageInfo<Employee>();
        //分页公式    第几页 = （第几页-1） * 一页的个数
        Integer start = (page - 1) * pageSize;
        List<Employee> employees = employeeMapper.page(name, start, pageSize);
        //records：当前页面内容，是个数组[]
        pageInfo.setRecords(employees);
        //size：每页显示条数
        pageInfo.setSize(pageSize);
        //current：当前页码
        pageInfo.setCurrent(page);

        //计算 total(总条数)(通过名字) 的方法
        long count = employeeMapper.countEmplyee(name);

        //total：总条数
        pageInfo.setTotal(count);
        return pageInfo;

    }

    //新增员工
    @Override
    public boolean addEmployee(Employee employee) {
        //雪花数生成id
        String id = IdUtil.getSnowflakeNextIdStr();
        //md5加密密码
        String password = SecureUtil.md5("123456");
        //设置激活状态
        int status = 1;

        employee.setId(id);
        employee.setPassword(password);
        employee.setStatus(status);

        int res = employeeMapper.addEmployee(employee);

        return res == 1;

    }

    //更新员工
    @Override
    public boolean updateEmployee(Employee employee) {

        employee.setUpdateTime(LocalDateTime.now());

        int res = employeeMapper.updateEmployee(employee);
        return res == 1;
    }
}
